<?php

/**
 * This is the model class for table "dbm_table".
 *
 * The followings are the available columns in table 'dbm_table':
 * @property string $table_name Table Name
 */
class DbmTable extends DbmActiveRecord
{
	protected $_dbmTableSchema = null;
	
	public function findByTableName($table_name) {
		return $this->findByAttributes(array('table_name' => $table_name));
	}
	
	public function __get($name) {
		if(parent::__isset($name)) {
			return parent::__get($name);
		} elseif(isset($this->getDbmTableSchema()->$name)) {
			return $this->getDbmTableSchema()->$name;
		} else {
			return parent::__get($name);
		}
	}
	
	public function getHasPhysicsTable() {
		return $this->getDbmTableSchema()->getHasPhysicsTable();
	}
	
	public function getDbmTableSchema() {
		if($this->_dbmTableSchema === null) {
			$orgSchema = Yii::app()->db->getSchema()->getTable($this->table_name);
			$this->_dbmTableSchema = new DbmTableSchema(
				$orgSchema
			);
		}
		return $this->_dbmTableSchema;
	}
	
	public function getDescription() {
		if($this->getDbmTableSchema()->getComment()) {
			return $this->getDbmTableSchema()->getComment();
		} else {
			return $this->desc;
		}
	}
	
	/**
	 * Returns the static model of the specified AR class.
	 * @return DbmTable the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
	
	public function getMdcClass() {
		return 'dbMonitor.models.metadata.DbmTableMetadata';
	}
	
	/**
	 * behavior 如果要继承使用父类的 behaviors 请使用 array_merge 方法
	 * 否则直接返回 array 数组
	 */
	public function behaviors() {
		return array_merge(parent::behaviors(), array(
		));
	}
	
	/**
	 * @return array relational rules.
	 */
	public function relations() {
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array_merge(parent::relations(), array(
			'history' => array(self::HAS_MANY, 'DbmHistory', 'table_name'),
		));
	}
	
	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules() {
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array_merge(parent::rules(), array(
		));
	}
	
	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels() {
		return array_merge(parent::attributeLabels(), array(
			'comment' => '表注释'
		));
	}
	
	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('table_name',$this->table_name,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
}

class DbmTableSchema extends CComponent {
	
	protected $_table = null;
	protected $_columns = array();
	protected $_comment;
	protected $_columnsExtInfo;
	
	public function __construct($table) {
		$this->_table = $table;
	}

	public function getHasPhysicsTable() {
		return is_object($this->_table);
	}
	
	public function getColumns() {
		if(empty($this->_columns)) {
			$infos = $this->getColumnsExtInfo();
			foreach($this->_table->columns as $column) {
				$dbColumn = new DbmTableColumnSchema($column);
				foreach($infos[$column->name] as $k=>$v) {
					$dbColumn->$k = $v;
				}
				$this->_columns[$column->name] = $dbColumn;
			}
		}
		return $this->_columns;
	}
	
	public function getColumnsExtInfo() {
		
		if(!$this->_columnsExtInfo) {
			$dbName = $this->getDbName();
			$result = Yii::app()->db->createCommand("
				select column_name, column_comment, data_type,
				ordinal_position
				from information_schema.columns 
				where table_schema ='{$dbName}'  
				and table_name = '{$this->_table->name}'")->queryAll();
			$infos = array();
			foreach($result as $column) {
				$infos[$column['column_name']] = array(
					'comment' => $column['column_comment'],
					'dataType' => $column['data_type'],
					'position' => $column['ordinal_position'],
				);
			}
	
			$this->_columnsExtInfo = $infos;
		}
		return $this->_columnsExtInfo;
	}
	
	
	public function getComment() {
		if(!$this->_comment && $this->getHasPhysicsTable()) {
			$dbName = $this->getDbName();
			$result = Yii::app()->db->createCommand("
					SELECT TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES
					WHERE TABLE_SCHEMA ='{$dbName}'  
					AND TABLE_NAME = '{$this->_table->name}'")->queryRow();
			
			$this->_comment = $result['TABLE_COMMENT'];
		}
		return CPropertyValue::ensureString($this->_comment);
	}
	
	public function __get($name) {
		if(parent::__isset($name)) {
			return parent::__get($name);
		} elseif(isset($this->_table->$name)) {
			return $this->_table->$name;
		}
		return parent::__get($name);
	}
	
	public function __isset($name) {
		if(parent::__isset($name) || isset($this->_table->$name)) {
			return true;
		}
		return false;
	}
	
	public function getDbName() {
		$connectionString = Yii::app()->db->connectionString;
		preg_match('/dbname=(.*)/i', $connectionString, $matches);
		$dbName = $matches[1];
		return $dbName;
	}
	
}

class DbmTableColumnSchema extends CComponent {
	
	protected $_column;
	public $comment;
	public $dataType;
	public $position;
	
	public function __construct(CDbColumnSchema $column) {
		$this->_column = $column;
	}
	
	public function __get($name) {
		if(isset($this->_column->$name) || 
			property_exists($this->_column, $name)) {
			return $this->_column->$name;
		} else {
			return parent::__get($name);
		}
	}
	
	
}